﻿using DataBaseConnect.IRepositories;
using Entity;
using Entity.Dto;
using System.Collections.Generic;
using System.Linq;

namespace DataBaseConnect.Repositories
{
    /// <summary>
    /// 用户管理仓储实现
    /// </summary>
    public class UserRepository : FonourRepositoryBase<User>, IUserRepository
    {
        public UserRepository(MyDataBase dbcontext) : base(dbcontext)
        {

        }

        /// <summary>
        /// 根据用户名和密码获取用户信息
        /// </summary>
        /// <param name="Name">用户名</param>
        /// <param name="Passowrd">密码</param>
        /// <returns></returns>
        public User GetUser(string Name, string Passowrd)
        {
            return _dbContext.Set<User>().FirstOrDefault(m => m.UserName == Name && m.Password == Passowrd);
        }

        /// <summary>
        /// 获取所有用户信息（包括部门名称）&&查询
        /// </summary>
        /// <param name="UserName">用户名称</param>
        /// <returns></returns>
        public List<UserDto> GetUserOrDepartment(string UserName)
        {
            var userId = new List<User>();
            if (!string.IsNullOrWhiteSpace(UserName))
            {
                userId = _dbContext.Set<User>().Where(d => d.UserName == UserName).ToList();
            }
            else
            {
                userId = _dbContext.Set<User>().ToList();
            }
            //关联查询
            var userDto = (from q in _dbContext.Set<Department>().ToList()
                           join m in userId.ToList()
                           on q.Id equals m.DepartmentId
                           select new UserDto
                           {
                               DepartmentName = q.DepartmentName,
                               Age = m.Age,
                               UserId = m.UserId,
                               UserName = m.UserName,
                               Password = m.Password,
                               Sex = m.Sex
                           }).ToList();
            return userDto;
        }
    }
}
